//
//  LXActivityViewController.m
//  LXLessDemo
//
//  Created by LX on 16/2/12.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXActivityViewController.h"
#import "LXPullDownView.h"
#import "LXCustomNavView.h"
#import "LXNetPhotoViewController.h"
#import "LXListScrollView.h"
#import "UIImage+Extension.h"

#import <AssetsLibrary/ALAsset.h>

#import <AssetsLibrary/ALAssetsLibrary.h>

#import <AssetsLibrary/ALAssetsGroup.h>

#import <AssetsLibrary/ALAssetRepresentation.h>
#import "LXCustomImagePickerController.h"


@interface LXActivityViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    BOOL isCamer;
}
@property (strong,nonatomic) LXPullDownView *pulDownView;
@property (strong,nonatomic) LXCustomNavView *customNavView;
@property (strong,nonatomic) UIButton *photoUpBtn;
@property (strong,nonatomic) NSMutableArray *images;
@property (strong,nonatomic) UIImage *showImage;
@property (strong,nonatomic) LXListScrollView *photoScrollView;
@property (strong,nonatomic) UIImageView *mainInmageView;
@property (assign,nonatomic) BOOL isEndLvJing;
@property (strong,nonatomic) LXCustomImagePickerController *customPicke;

@end

@implementation LXActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isEndLvJing = NO;
    self.view.backgroundColor = backColor;
    [self settingTestDatfa];
    self.showImage = [UIImage imageNamed:self.images[1]];
    [self addNavView];
    [self addSelectPhoto];
}
-(void)addNavView{
    self.pulDownView = [[LXPullDownView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) downImage:[UIImage imageNamed:@"down"] upImage:[UIImage imageNamed:@"up"] text:@"相机胶卷"];
    __weak typeof(self) weakSelf = self;
    self.pulDownView.selectBlock = ^(BOOL isSelect){
        [weakSelf settingNavItemWithHeiden:isSelect];
        [weakSelf photoAction:nil];
    };
    
    self.customNavView = [[LXCustomNavView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 40) title:@""];
    [self.view addSubview:self.customNavView];
    [self.customNavView settingTitleView:self.pulDownView];
    //leftBarButton
    [self.customNavView settingBackBarButtonWithImage:[UIImage imageNamed:@"close"] text:nil sel:@selector(backButtonClick) target:self];
    //rightBarButton
    [self.customNavView settingRightBarButtonWithImage:nil text:@"下一步" sel:@selector(nexrButtonClick) target:self];
}
-(void)addSelectPhoto{
    // photo view
//    self.imgShowView = [[MRImgShowView alloc]
//                                  initWithFrame:CGRectMake(0, 40, CGRectGetWidth([UIScreen mainScreen].bounds), 320)
//                                  withSourceData:@[@""]
//                                  withIndex:0
//                                    image:[UIImage imageNamed:@"homenew_tupian_1"]
//                        ];
//    self.imgShowView.userInteractionEnabled = YES;
//    self.imgShowView.tag = 41231;
//    self.imgShowView.selectBlock = ^(NSUInteger index) {
//        
//    };
//    
//    // 解决谦让
//    [self.imgShowView requireDoubleGestureRecognizer:[[self.view gestureRecognizers] lastObject]];
//    
//    [self.view addSubview:self.imgShowView];
    
    self.mainInmageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, CGRectGetWidth([UIScreen mainScreen].bounds), 320)];
    [self.mainInmageView setImage:self.showImage];
    [self.view addSubview:self.mainInmageView];
    
    self.photoUpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.photoUpBtn setFrame:CGRectMake(0, 0, 30, 30)];
    [self.photoUpBtn setImage:[UIImage imageNamed:@"photoUp"] forState:0];
    [self.photoUpBtn setImage:[UIImage imageNamed:@"phDown"] forState:UIControlStateSelected];
    self.photoUpBtn.center = CGPointMake(CGRectGetWidth([UIScreen mainScreen].bounds)/2.0, CGRectGetMaxY(self.mainInmageView.frame) + CGRectGetHeight(self.photoUpBtn.bounds)/2.0 + 5);
    [self.photoUpBtn addTarget:self action:@selector(photoUpBtnClic:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.photoUpBtn];
    
    _photoScrollView = [[LXListScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.photoUpBtn.frame) + 5, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds) - CGRectGetMaxY(self.photoUpBtn.frame) - 5)];
    __weak typeof(self) weakSelf = self;

    _photoScrollView.selectBock = ^(NSString *photoID){
        if ([photoID integerValue] == 0) {
            [weakSelf addSourceTypeCamera];
        }else{
            weakSelf.showImage = [UIImage imageNamed:photoID];
            [weakSelf.mainInmageView setImage:[UIImage imageNamed:photoID]];
        }
    };
    [self.view addSubview:_photoScrollView];
};
-(void )settingTestDatfa{
    
    self.images = [NSMutableArray array];
    for (int i = 0; i < 19; i++) {
        NSString *string = [NSString stringWithFormat:@"%d",i];
        [self.images addObject:string];
    }
}

-(void)settingNavItemWithHeiden:(BOOL)heiden{
    if (!heiden) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:0 target:self action:@selector(nexrButtonClick)];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:0 target:self action:@selector(backButtonClick)];

    }else{
        self.navigationItem.rightBarButtonItem = nil;
        self.navigationItem.leftBarButtonItem = nil;
        [self.navigationItem setHidesBackButton:YES];
    }
}
-(void)photoUpBtnClic:(UIButton *)sender{
    self.photoUpBtn.selected = !self.photoUpBtn.selected;
    [self editBeginEvent];
}
-(void)nexrButtonClick{
    NSLog(@"跳转！");
    if (!_isEndLvJing) {
        [self pPushPGEditSDKController];
        return;
    }
    [self lvJingEndClick];

}
-(void)lvJingEndClick{
    LXNetPhotoViewController *next = [[LXNetPhotoViewController alloc] init];
    next.image = self.showImage;
    self.isEndLvJing = NO;
    [self presentViewController:next animated:YES completion:^{
        ;
    }];
}
-(void)backButtonClick{
    NSLog(@"返回！");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setHidden:NO];
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
    self.view.transform = pTransform;
}
#pragma mark上移视图
-(void)editBeginEvent
{
    //创建一个线程用来延迟视图上弹
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(change) object:nil];
    [thread start];
}
- (void)change
{
    //线程睡眠0.2秒以实现视图延迟上弹
    [NSThread sleepForTimeInterval:0.1];
    //创建一个仿射变换，平移(0, -100)视图上移100像素
    CGAffineTransform transform = self.view.transform;
    CGAffineTransform pTransform;
    BOOL UP = NO;
    if (transform.ty < 0) {
        pTransform = CGAffineTransformMakeTranslation(0, 0);
        UP = NO;
    }
    else{
        pTransform = CGAffineTransformMakeTranslation(0, -(CGRectGetMaxY(self.mainInmageView.frame) - 15));
        UP = YES;
    }
    self.view.transform = pTransform;
    [self changePhotoScrollViewWithIsUp:UP];
}
-(void)changePhotoScrollViewWithIsUp:(BOOL)isUp{
    CGRect scrollFrame = _photoScrollView.frame;
    CGRect self_viewFrame = self.view.frame;

    if (isUp) {
        scrollFrame.size.height += (CGRectGetMaxY(self.mainInmageView.frame) - 15);
        self_viewFrame.size.height += (CGRectGetMaxY(self.mainInmageView.frame) - 15);
    }else{
        scrollFrame.size.height -= (CGRectGetMaxY(self.mainInmageView.frame) - 15);
        self_viewFrame.size.height -= (CGRectGetMaxY(self.mainInmageView.frame) - 15);
    }
    _photoScrollView.frame = scrollFrame;
    self.view.frame = self_viewFrame;

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(IOS7_OR_LATER)
    {
        self.navigationController.navigationBar.translucent = NO;
    }
    [self.navigationController.navigationBar setHidden:YES];
    isCamer = NO;
}

#pragma mark - UIImagePickerController
- (void)photoAction:(id)sender
{
    isCamer = YES;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    [picker setAllowsEditing:NO];
    picker.modalTransitionStyle =  UIModalTransitionStyleCoverVertical;
    picker.delegate = self;
//    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//    [self presentViewController:picker animated:YES completion:nil];
//    picker.cameraOverlayView.backgroundColor = [UIColor colorWithWhite:0.25 alpha:0.5];

    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//类别//UIImagePickerControllerSourceTypeSavedPhotosAlbum//时间轴
    [self presentViewController:picker animated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        [[UIApplication sharedApplication] setStatusBarHidden:YES
                                                withAnimation:UIStatusBarAnimationFade];
    }];
}

#pragma mark ==================自定义相机界面()
-(void)custonImagePicker{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //拍摄模式下打开
//    imagePicker.showsCameraControls = NO;
//    imagePicker.cameraViewTransform = CGAffineTransformScale(imagePicker.cameraViewTransform, 1.0, 1.0);
    self.customPicke = [[LXCustomImagePickerController alloc] initWithNibName:@"LXCustomImagePickerController" bundle:nil pickerConntroller:imagePicker];
    imagePicker.cameraOverlayView = self.customPicke.view;
    [self presentViewController:imagePicker animated:YES completion:^{
        ;
    }];
    

}
//拍照
-(void)addSourceTypeCamera{
    isCamer = YES;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    [picker setAllowsEditing:NO];
    picker.modalTransitionStyle =  UIModalTransitionStyleCoverVertical;
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }];
}
#pragma mark - UIImagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *originImage = [[info objectForKey:UIImagePickerControllerOriginalImage] fixOrientation];
    UIImage *previewImage = [UIImage imageWithData:UIImageJPEGRepresentation(originImage, 0.01)];
    
    if (previewImage) {
        self.showImage = [previewImage scaleToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 320)];
        [self.mainInmageView setImage:self.showImage];
//        self.view.backgroundColor = [UIColor colorWithPatternImage:self.showImage];
//        [self.imgShowView settingVContentFromImage:self.showImage];
//        self.imgShowView .backgroundColor = [UIColor redColor];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        ;
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    // bug fixes: UIIMagePickerController使用中偷换StatusBar颜色的问题
    if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}

#pragma mark - pg_edit_sdk_controller
- (void)pPushPGEditSDKController
{
    pg_edit_sdk_controller *editCtl = nil;
    {
        //构建编辑对象    Construct edit target
        pg_edit_sdk_controller_object *obje = [[pg_edit_sdk_controller_object alloc] init];
        {
            //输入原图  Input original
            obje.pCSA_fullImage = [self.showImage copy];
        }
        editCtl = [[pg_edit_sdk_controller alloc] initWithEditObject:obje withDelegate:self];
    }
    NSAssert(editCtl, @"Error");
    if (editCtl) {
        [self presentViewController:editCtl animated:YES completion:^{
            //do nothing
        }];

        
        /*
         [self.navigationController pushViewController:editCtl animated:YES];
         */
    }
}
- (void)dgPhotoEditingViewControllerDidCancel:(UIViewController *)pController withClickSaveButton:(BOOL)isClickSaveBtn
{
//    [self.navigationController popViewControllerAnimated:YES];
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf lvJingEndClick];
    }];
}

- (void)dgPhotoEditingViewControllerDidFinish:(UIViewController *)pController
                                       object:(pg_edit_sdk_controller_object *)pOjbect
{
    //获取效果小图    Obtain effect thumbnail
    UIImage *image = [UIImage imageWithData:pOjbect.pOutEffectDisplayData];
    NSAssert(image, @" ");
//    [self.mV_displayImageView pSetupPreviewImage:image];
//    //启动一个完成界面  Start a completed screen
//    [self pPushCompleteViewController];
    
    //获取效果大图    Obtain effect large image
    UIImage *imageOri = [UIImage imageWithData:pOjbect.pOutEffectOriData];
    NSAssert(imageOri, @" ");
    self.isEndLvJing = YES;
    self.showImage = imageOri;
    [self.mainInmageView setImage:self.showImage];
    //保存到相册     Save to album
    UIImageWriteToSavedPhotosAlbum(imageOri, nil, NULL, NULL);
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf lvJingEndClick];
    }];

}

- (void)dgPhotoEditingViewControllerShowLoadingView:(UIView *)view
{
    ;
}

- (void)dgPhotoEditingViewControllerHideLoadingView:(UIView *)view
{
    ;;
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}
//获取相册的所有图片
//- (void)reloadImagesFromLibrary
//{
//    self.images = [[NSMutableArray alloc] init];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        
//        @autoreleasepool {
//            ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
//                NSLog(@"相册访问失败 =%@", [myerror localizedDescription]);
//                if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
//                    NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
//                }else{
//                    NSLog(@"相册访问失败.");
//                }
//            };
//            
//            ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){
//                if (result!=NULL) {
//                    
//                    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
//                        
//                        NSString *urlstr=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url
//                        [self.images addObject:urlstr];
//                        //NSLog(@"urlStr is %@",urlstr);
//                        /*result.defaultRepresentation.fullScreenImage//图片的大图
//                         result.thumbnail                             //图片的缩略图小图
//                         //                    NSRange range1=[urlstr rangeOfString:@"id="];
//                         //                    NSString *resultName=[urlstr substringFromIndex:range1.location+3];
//                         //                    resultName=[resultName stringByReplacingOccurrencesOfString:@"&ext=" withString:@"."];//格式demo:123456.png
//                         */
//                    }
//                }
//            };
//            
//            ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroupsEnumeration = ^(ALAssetsGroup* group, BOOL* stop){
//                
//                if (group == nil)
//                {
//                    
//                }
//                
//                if (group!=nil) {
//                    NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
//                    NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
//                    
//                    NSString *g1=[g substringFromIndex:16 ] ;
//                    NSArray *arr=[[NSArray alloc] init];
//                    arr=[g1 componentsSeparatedByString:@","];
//                    NSString *g2=[[arr objectAtIndex:0] substringFromIndex:5];
//                    if ([g2 isEqualToString:@"Camera Roll"]) {
//                        g2=@"相机胶卷";
//                    }
//                    NSString *groupName=g2;//组的name
//                    
//                    [group enumerateAssetsUsingBlock:groupEnumerAtion];
//                }
//                
//            };
//            
//            ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
//            [library enumerateGroupsWithTypes:ALAssetsGroupAll
//                                   usingBlock:libraryGroupsEnumeration
//                                 failureBlock:failureblock];
//        }
//        
//    });
//}
@end
